﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Model.NoNet;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace DFGK_WMS.Repository
{
    public class TTransferBinOrderRepository : BaseRepository<TTransferBinOrder>, ITTransferBinOrderRepository
    {
        private readonly SqliteContext sqlite;

        public TTransferBinOrderRepository(DFGK_DB context, IMapper mapper, SqliteContext sqlite) : base(context, mapper)
        {
            this.sqlite = sqlite;
        }

        /// <summary>
        /// 提交数据 （增加/修改/删除）
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool SubmitTransferBinOrderData(TTransferBinOrderDTO m)
        {
            //使用事务的原子性
            using (var trans = Context.Database.BeginTransaction())
            {
                try
                {
                    TTransferBinOrder tran = new TTransferBinOrder();
                    tran = Mapper.Map<TTransferBinOrder>(m);
                    bool isAdd = m.Id <= 0;
                    #region 添加移库单
                    if (isAdd)
                    {
                        tran.CreateUserId = m.CreateUserId;
                        tran.CreateUserName = m.CreateUserName;
                        tran.CreateDate = m.CreateDate;
                        tran.ModifyDate = DateTime.Now;
                        tran.ModifyUserId = m.ModifyUserId;
                        tran.ModifyUserName = m.ModifyUserName;
                        tran.Remark = m.Remark;
                        tran.Reason = m.Reason;
                        tran.CompanyName = "";//com.Name==null ? null : com.Name;
                        tran.Status = 0;

                        Context.TTransferBinOrders.Add(tran);
                        Context.SaveChanges();
                        List<TTransferBinOrderDetail> transferBinOrderDetails = new List<TTransferBinOrderDetail>();
                        if (m.OrderDetailList != null && m.OrderDetailList.Count > 0)
                        {
                            foreach (var item in m.OrderDetailList)
                            {
                                TTransferBinOrderDetail transferBinOrderDetail1 = new TTransferBinOrderDetail();
                                transferBinOrderDetail1.OrderId = tran.Id;
                                transferBinOrderDetail1.OrderSn = tran.OrderSn;
                                transferBinOrderDetail1.CreateUserId = item.CreateUserId;
                                transferBinOrderDetail1.CreateUserName = item.CreateUserName;
                                transferBinOrderDetail1.CreateDate = item.CreateDate;
                                transferBinOrderDetail1.ModifyUserId = item.ModifyUserId;
                                transferBinOrderDetail1.ModifyUserName = item.ModifyUserName;
                                transferBinOrderDetail1.ModifyDate = item.ModifyDate;
                                transferBinOrderDetail1.MaterialCategoryId = item.MaterialCategoryId;
                                transferBinOrderDetail1.MaterialCategoryName = item.MaterialCategoryName;
                                transferBinOrderDetail1.MaterialId = item.MaterialId;
                                transferBinOrderDetail1.MaterialName = item.MaterialName;
                                transferBinOrderDetail1.MaterialCode = item.MaterialCode;
                                transferBinOrderDetail1.FromLocationId = item.FromLocationId;
                                transferBinOrderDetail1.FromLocationCode = item.FromLocationCode;
                                transferBinOrderDetail1.FromLocationName = item.FromLocationName;
                                transferBinOrderDetail1.ToLocationCode = item.ToLocationCode;
                                transferBinOrderDetail1.ToLocationId = item.ToLocationId;
                                transferBinOrderDetail1.ToLocationName = item.ToLocationName;
                                transferBinOrderDetail1.ModelSpec = item.ModelSpec;
                                transferBinOrderDetail1.QualityState = item.QualityState;
                                transferBinOrderDetail1.AvailableQty = item.AvailableQty;
                                transferBinOrderDetail1.UnitName = item.UnitName;
                                transferBinOrderDetail1.Remark = item.Remark;
                                transferBinOrderDetail1.Status = 0;
                                #region 添加移库单明细
                                Context.TTransferBinOrderDetails.Add(transferBinOrderDetail1);
                                Context.SaveChanges();
                                #endregion
                            }
                        }
                    }
                    #endregion

                    #region 修改/删除 移库单和移库单明细
                    else
                    {
                        #region 修改移库单
                        tran.ModifyDate = DateTime.Now;
                        tran.ModifyUserId = m.ModifyUserId;
                        tran.ModifyUserName = m.ModifyUserName;
                        tran.CompanyName = "";//com.Name == null ? null : com.Name;
                        Context.TTransferBinOrders.Update(tran);
                        Context.SaveChanges();
                        #endregion

                        var listDetail = Context.TTransferBinOrderDetails.Where(t => t.OrderId == tran.Id).ToList();
                        if (listDetail != null && listDetail.Count > 0)
                        {
                            //foreach (var item in listDetail)
                            // {
                            Context.TTransferBinOrderDetails.RemoveRange(listDetail);
                            // }
                            foreach (var item in m.OrderDetailList)
                            {

                                item.OrderId = tran.Id;
                                item.OrderSn = tran.OrderSn;
                                item.CreateUserId = tran.CreateUserId;
                                item.CreateUserName = tran.CreateUserName;
                                item.CreateDate = DateTime.Now;
                                item.ModifyUserId = tran.ModifyUserId;
                                item.ModifyUserName = tran.ModifyUserName;
                                item.ModifyDate = tran.ModifyDate;


                                Context.TTransferBinOrderDetails.Add(item);
                                //Context.SaveChanges();
                            }
                        }
                    }
                    #endregion
                    Context.SaveChanges();
                    //提交事务
                    trans.Commit();
                    return true;
                }
                catch (Exception)
                {
                    //事务回滚
                    trans.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 删除移库单
        /// </summary>
        /// <param name="tid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelTransferBinOrder(int tid)
        {
            var mobj = Context.TTransferBinOrders.Find(tid);
            if (mobj != null)
            {
                Context.TTransferBinOrders.Remove(mobj);
            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 获取可用仓位
        /// </summary>
        /// <param name="fromLocationId"></param>
        /// <param name="isPriorityFilling"></param>
        /// <param name="filterType"></param>
        /// <param name="toLogicalPartCode"></param>
        /// <returns></returns>
        public List<TCell> GetEnabledCellListByFromLocationId(string? toLogicalPartCode, int FromLocationId, bool isPriorityFilling = false, int filterType = 1)
        {
            var cellQuery = Context.TCells.AsNoTracking().ToList();
            var shelfQuery = Context.TShelves;
            var inventoryQuery = Context.TInventories;
            var inventory = inventoryQuery.Where(i => i.LocationId == FromLocationId).FirstOrDefault();

            if (inventory is null)
            {
                return null;
            }
            if (inventory.IsMultPallet == true)
            {
                toLogicalPartCode = "MultPallet";//花盘定死
            }
            List<int?> list = null;
            if (isPriorityFilling)
            {
                if (filterType == 1)
                {
                    list = inventoryQuery.Where(i => i.MaterialId == inventory.MaterialId && i.Status == 1).Select(i => i.LocationId).ToList();
                }
                else if (filterType == 2)
                {
                    list = inventoryQuery.Where(i => i.MaterialId == inventory.MaterialId && i.Status == 1).Select(i => i.LocationId).ToList();
                }
                else
                {
                    list = inventoryQuery.Where(i => i.Status == 1).Select(i => i.LocationId).ToList();
                }
                cellQuery = cellQuery.Where(c => list.Contains(c.Id) && c.Status == (int)EmCellStatus.Normal && c.IsLock == false && c.BusinessType == 0 && c.FullStatus == 0 && c.HeightType >= inventory.RealHeightType && c.LayerNo == inventory.LocationLayerNo && c.LineNo == inventory.LocationLineNo && c.ColumnNo > inventory.LocationColumnNo && c.DepthIndex == inventory.LocationDepth).ToList();
            }
            else
            {
                cellQuery = cellQuery.Where(c => c.Status == (int)EmCellStatus.Normal && c.FullStatus == 0 && c.IsLock == false && c.BusinessType == 0 && c.HeightType >= inventory.RealHeightType).ToList();
            }
            if (!string.IsNullOrEmpty(toLogicalPartCode))
            {
                cellQuery = cellQuery.Where(t => t.LogicalPartCode == toLogicalPartCode).ToList();
            }
            return cellQuery.OrderBy(c => c.HeightType)
                .ThenBy(c => c.LineNo)
                .ThenBy(c => c.DistanceValue)
                .ThenBy(c => c.LayerNo)
                .ThenBy(c => c.ColumnNo)
                .ThenBy(c => c.DepthIndex)
                .ToList();
        }

        /// <summary>
        /// 查询单个移库信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TTransferBinOrder GetTransferBinOrderById(int id)
        {
            return Context.TTransferBinOrders.Find(id);
            //TTransferBinOrderDTO Tdto = new TTransferBinOrderDTO();
            //Tdto = Mapper.Map<TTransferBinOrderDTO>(tran);
            //Tdto.OrderDetailList = Context.TTransferBinOrderDetails.Where(t => t.OrderId == tran.Id).ToList();

        }

        /// <summary>
        /// 查询全部移库单信息
        /// </summary>
        /// <param name="kname"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TTransferBinOrder> GetTransferBinOrderList(string AsNoTracking, string? StartTime, string? EndTime, string? CellName, int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                var list = Context.TTransferBinOrders.AsQueryable();
                if (!string.IsNullOrEmpty(AsNoTracking))
                {
                    list = list.Where(x => x.OrderSn.Contains(AsNoTracking));
                }

                if (StartTime != null && EndTime != null)
                {
                    string StartdateString = StartTime;
                    DateTime Startdate = DateTime.Parse(StartdateString);
                    string EnddateString = EndTime;
                    DateTime Enddate = DateTime.Parse(EnddateString);
                    list = list.Where(x => x.CreateDate >= Startdate && x.CreateDate <= Enddate);

                }

                totalCount = list.Count();
                return list.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            catch (Exception)
            {
                throw;
            }
        }



        public List<TTransferBinOrderDTO> GetTransferBinList(string AsNoTracking, string? StartTime, string? EndTime, string? CellName, int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                var OrderList = Context.TTransferBinOrders.AsQueryable().ToList();
                var OrderDetailList = Context.TTransferBinOrderDetails.AsQueryable();

                if (!string.IsNullOrEmpty(AsNoTracking))
                {
                    OrderList = OrderList.Where(x => x.OrderSn.Contains(AsNoTracking)).ToList();
                }

                if (StartTime != null && EndTime != null)
                {
                    string StartdateString = StartTime;
                    DateTime Startdate = DateTime.Parse(StartdateString);
                    string EnddateString = EndTime;
                    DateTime Enddate = DateTime.Parse(EnddateString);
                    OrderList = OrderList.Where(x => x.CreateDate >= Startdate && x.CreateDate <= Enddate).ToList();

                }
                if (CellName != null)
                {
                    OrderDetailList = OrderDetailList.Where(x => x.ToLocationName.Contains(CellName));
                }


                List<TTransferBinOrderDTO> transferBinOrderDTO = new List<TTransferBinOrderDTO>();

                foreach (var item in OrderList)
                {
                    TTransferBinOrderDTO transferBinOrderDTO1 = new TTransferBinOrderDTO();
                    transferBinOrderDTO1.Id = item.Id;
                    transferBinOrderDTO1.OrderSn = item.OrderSn;
                    transferBinOrderDTO1.BillType = item.BillType;
                    transferBinOrderDTO1.Status = item.Status;
                    transferBinOrderDTO1.SourceType = item.SourceType;
                    transferBinOrderDTO1.CompanyId = item.CompanyId;
                    transferBinOrderDTO1.CompanyName = item.CompanyName;
                    //transferBinOrderDTO1.Priority = item.Priority;
                    transferBinOrderDTO1.Erpcode = item.Erpcode;
                    transferBinOrderDTO1.Reason = item.Reason;
                    transferBinOrderDTO1.Remark = item.Remark;
                    transferBinOrderDTO1.CreateUserId = item.CreateUserId;
                    transferBinOrderDTO1.CreateUserName = item.CreateUserName;
                    transferBinOrderDTO1.CreateDate = item.CreateDate;
                    transferBinOrderDTO1.ModifyUserId = item.ModifyUserId;
                    transferBinOrderDTO1.ModifyUserName = item.ModifyUserName;
                    transferBinOrderDTO1.ModifyDate = item.ModifyDate;
                    transferBinOrderDTO1.SubmitUserId = item.SubmitUserId;
                    transferBinOrderDTO1.SubmitUserName = item.SubmitUserName;
                    transferBinOrderDTO1.SubmitDate = item.SubmitDate;
                    transferBinOrderDTO1.AuditUserId = item.AuditUserId;
                    transferBinOrderDTO1.AuditUserName = item.AuditUserName;
                    transferBinOrderDTO1.AuditDate = item.AuditDate;

                    // 添加明细
                    foreach (var detail in OrderDetailList.Where(x => x.OrderSn == item.OrderSn).ToList())
                    {
                        transferBinOrderDTO1.OrderDetailList.Add(detail);
                    }

                    transferBinOrderDTO.Add(transferBinOrderDTO1);
                }

                totalCount = transferBinOrderDTO.Count();

                // 按照订单创建时间降序排列并分页返回结果
                transferBinOrderDTO = transferBinOrderDTO.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

                return transferBinOrderDTO;
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 查看移库单的详细信息
        /// </summary>
        /// <param name="Id">移库单id</param>
        /// <returns></returns>
        public TTransferBinOrderDTO SelectTransferBinOrder(int Id)
        {
            var Trans = Context.TTransferBinOrders.FirstOrDefault(t => t.Id == Id);
            if (Trans != null)
            {
                TTransferBinOrderDTO dto = new TTransferBinOrderDTO();
                dto = Mapper.Map<TTransferBinOrderDTO>(Trans);
                dto.OrderDetailList = Context.TTransferBinOrderDetails.Where(t => t.OrderId == dto.Id).ToList();
                return dto;
            }
            return null;
        }


        /// <summary>
        /// 修改移库单信息
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateTransferBinOrder(TTransferBinOrder t)
        {
            try
            {
                t.ModifyDate = DateTime.Now;
                t.ModifyUserId = t.ModifyUserId;
                t.ModifyUserName = t.ModifyUserName;
                Context.TTransferBinOrders.Update(t);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {

                throw;
            }
        }

        public bool SubmitTranState(SubmitTranDTO submitTranDTO)
        {
            var user = Context.TUsers.Where(u => u.RealName == submitTranDTO.RealName && u.JobNo == submitTranDTO.JoNO).FirstOrDefault();
            if (user != null)
            {
                var tran = Context.TTransferBinOrders.Where(t => t.Id == submitTranDTO.TranId).FirstOrDefault();
                tran.Status = 2;
                if (UpdateTransferBinOrder(tran))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 添加数据到sqlite
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool AddSqliteDetail(TTransferBinOrderDTO m, out string message)
        {
            using var tran = Context.Database.BeginTransaction();
            try
            {
                message = "";
                //创建表（如果不存在）
                bool aa = sqlite.Database.EnsureCreated();
                // 设置连接字符串
                //string connectionString = "Data Source=/root/WMS/PC-Service/wwwroot/file/chat.db";
                string connectionString = "Data Source=.\\wwwroot\\file\\chat.db";

                // 创建连接对象
                using (var connection = new SqliteConnection(connectionString))
                {
                    // 打开连接
                    connection.Open();

                    // 创建SQL命令对象
                    using (var command = connection.CreateCommand())
                    {
                        // 设置清空缓存的SQL语句
                        command.CommandText = "PRAGMA cache_size=0;";

                        // 执行SQL命令
                        command.ExecuteNonQuery();

                        Console.WriteLine("Cache cleared.");
                    }

                    // 关闭连接
                    connection.Close();
                }
                List<TTransferBinOrderDetails> childrenss = new List<TTransferBinOrderDetails>();
                foreach (var item in m.OrderDetailList)
                {
                    TTransferBinOrderDetails transferBinOrderDetails = new TTransferBinOrderDetails();
                    transferBinOrderDetails.MaterialId = item.MaterialId;
                    transferBinOrderDetails.MaterialName = item.MaterialName;
                    transferBinOrderDetails.FromLocationId = item.FromLocationId;
                    transferBinOrderDetails.FromLocationName = item.FromLocationName;
                    transferBinOrderDetails.FromLocationCode = item.FromLocationCode;
                    childrenss.Add(transferBinOrderDetails);
                }

                var Json = JsonConvert.SerializeObject(m.OrderDetailList);
                string OrderSnByError = "";
                var TTransferBinModes = new TTransferBinModes();
                TTransferBinModes.Id = m.Id;
                TTransferBinModes.OrderSn = m.OrderSn;
                OrderSnByError = m.OrderSn;
                TTransferBinModes.BillType = m.BillType;
                TTransferBinModes.Reason = m.Reason;
                TTransferBinModes.Remark = m.Remark;
                TTransferBinModes.JsonData = Json;

                sqlite.TTransferBinModes.Add(TTransferBinModes);

                if (sqlite.SaveChanges() <= 0)
                {
                    tran.Rollback();
                    message = "移库数据添加失败! 单号:" + OrderSnByError;
                    return false;
                }
                tran.Commit();
                message = "移库单添加成功";
                return true;
            }
            catch
            {
                tran.Rollback();
                message = "移库单添加失败!";
                return false;
            }


        }


        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool UpdTTransferBinDetailDtoStatus(TTransferBinDetailDto m, out string message)
        {
            var robj = Context.TTransferBinOrders.Find(m.Id);

            if (robj != null)
            {
                switch (robj.Status)
                {
                    case 0:
                        var uobj = Context.TUsers.FirstOrDefault(x => x.Id == m.NowUserId);
                        if (uobj != null)
                        {
                            robj.SubmitUserId = m.NowUserId;
                            robj.SubmitUserName = m.NowUserRealName;
                            robj.SubmitDate = DateTime.Now;
                            robj.Remark = m.Remark;
                            //修改为：审核通过
                            robj.Status = 2;
                            Context.TTransferBinOrders.Update(robj);
                            break;
                        }
                        message = "工号有误！";
                        return false;

                    case 1:
                        break;

                    case 2:
                        robj.ModifyUserId = m.NowUserId;
                        robj.ModifyUserName = m.NowUserRealName;
                        robj.ModifyDate = DateTime.Now;
                        //修改为：作业中
                        robj.Status = 3;
                        Context.TTransferBinOrders.Update(robj);
                        break;

                    case 3:
                        robj.ModifyUserId = m.NowUserId;
                        robj.ModifyUserName = m.NowUserRealName;
                        robj.ModifyDate = DateTime.Now;
                        //修改为：已完成
                        robj.Status = 4;
                        Context.TTransferBinOrders.Update(robj);
                        break;

                    default:
                        break;
                }
                message = "修改成功！";
                return Context.SaveChanges() > 0;
            }
            message = "修改失败！";
            return false;
        }


        /// <summary>
        /// 根据OrderSn获取数据
        /// </summary>
        /// <param name="OrderSn"></param>
        /// <returns></returns>
        public List<TTransferBinOrderDTO> GetTTransferBinByOrderSn(string OrderSn)
        {
            if (OrderSn == null)
            {
                return null;
            }

            var detailsList = Context.TTransferBinOrderDetails.Where(x => x.OrderSn == OrderSn).ToList();
            var result = new List<TTransferBinOrderDTO>();

            foreach (var detail in detailsList)
            {
                var existingDto = result.FirstOrDefault(dto => dto.OrderSn == detail.OrderSn);
                if (existingDto == null)
                {
                    existingDto = new TTransferBinOrderDTO { OrderSn = detail.OrderSn };
                    result.Add(existingDto);
                }
                existingDto.OrderDetailList.Add(detail);
            }

            return result;
        }


        /// <summary>
        /// 读取sqlite数据库数据
        /// </summary>
        /// <returns></returns>
        public bool SubmitTransferBin(out string message)
        {
            using var tran = Context.Database.BeginTransaction();
            try
            {
                message = "";
                //创建表（如果不存在）
                sqlite.Database.EnsureCreated();

                var list = sqlite.SubmitTTransferBin.AsQueryable();

                if (list == null || !list.Any())
                {
                    message = "移库单未查询到数据";
                    return false;
                }
                string OrderSn = "";//初始单号
                string OrderSnDouble = "";//当前单号
                string OrderSnThree = "";//上个单号
                List<TTransferBinOrderDTO> dto = new List<TTransferBinOrderDTO>();

                foreach (var item in list)
                {
                    TTransferBinOrderDTO transferBinOrderDTO = new TTransferBinOrderDTO();
                    //TTransferBinOrderDetail transferBinOrderDetail = new TTransferBinOrderDetail();
                    //TTransferBinOrder transferBinOrder = new TTransferBinOrder();
                    TTransferBinOrderDetail transferBinOrderDetails = Context.TTransferBinOrderDetails.Where(x => x.OrderSn == item.OrderSn && x.MaterialId == item.MaterialId).First();
                    transferBinOrderDetails.OrderSn = item.OrderSn;
                    transferBinOrderDetails.MaterialId = item.MaterialId;
                    transferBinOrderDetails.MaterialName = item.MaterialName;
                    transferBinOrderDetails.FromLocationName = item.FromLocationName;
                    transferBinOrderDetails.FromLocationCode = item.FromLocationCode;
                    transferBinOrderDetails.ToLocationCode = item.ToLocationCode;
                    transferBinOrderDetails.ToLocationName = Context.TCells.First(x => x.Code == item.ToLocationCode).Name;
                    transferBinOrderDetails.ToLocationId = Context.TCells.First(x => x.Code == item.ToLocationCode).Id;
                    transferBinOrderDetails.Status = 4;
                    Context.TTransferBinOrderDetails.Update(transferBinOrderDetails);
                    if (Context.SaveChanges() <= 0)
                    {
                        message = "更新明细数据失败";
                        return false;
                    }
                    var existingOrder = Context.TTransferBinOrders.FirstOrDefault(o => o.OrderSn == item.OrderSn);
                    if (existingOrder != null)
                    {
                        existingOrder.Status = 4;
                        Context.TTransferBinOrders.Update(existingOrder);
                    }
                    transferBinOrderDTO.OrderDetailList.Add(transferBinOrderDetails);
                    dto.Add(transferBinOrderDTO);

                    if (OrderSn == OrderSnDouble)
                    {
                        if (OrderSnThree != "" && OrderSnDouble == OrderSnThree)
                        {
                            var TransferBinList = sqlite.SubmitTTransferBin.Where(x => x.OrderSn == item.OrderSn).ToList();
                            sqlite.SubmitTTransferBin.RemoveRange(TransferBinList);
                            var TransferBinModesList = sqlite.TTransferBinModes.Where(x => x.OrderSn == item.OrderSn).ToList();
                            sqlite.TTransferBinModes.RemoveRange(TransferBinModesList);
                            if (sqlite.SaveChanges() <= 0)
                            {
                                tran.Rollback();
                                message = "移库数据更新失败!";
                                return false;
                            }
                        }

                    }
                    else
                    {
                        if (OrderSnDouble != OrderSnThree)
                        {
                            var TransferBinList = sqlite.SubmitTTransferBin.Where(x => x.OrderSn == item.OrderSn).ToList();
                            sqlite.SubmitTTransferBin.RemoveRange(TransferBinList);
                            var TransferBinModesList = sqlite.TTransferBinModes.Where(x => x.OrderSn == item.OrderSn).ToList();
                            sqlite.TTransferBinModes.RemoveRange(TransferBinModesList);
                            if (sqlite.SaveChanges() <= 0)
                            {
                                tran.Rollback();
                                message = "移库数据更新失败!";
                                return false;
                            }
                        }
                    }
                    OrderSnThree = item.OrderSn;

                }
                string OrderSnByError = "";
                //修改仓位
                foreach (var item in dto.SelectMany(x => x.OrderDetailList))
                {
                    var inventories = Context.TInventories.Where(x => x.MaterialId == item.MaterialId && x.LocationCode == item.FromLocationCode).ToList();
                    foreach (var inventory in inventories)
                    {
                        var existingOrder = Context.TInventories.FirstOrDefault(o => o.MaterialId == item.MaterialId);
                        if (existingOrder != null)
                        {
                            existingOrder.LocationName = Context.TCells.Where(x => x.Code == item.ToLocationCode).First().Name;
                            existingOrder.LocationCode = item.FromLocationCode;
                            Context.TInventories.Update(existingOrder);
                        }

                        inventory.LocationCode = list.FirstOrDefault(x => x.MaterialId == item.MaterialId)?.ToLocationCode;
                        TInventoryLog inventoryLog = new TInventoryLog();
                        inventoryLog.SourceType = 5;
                        inventoryLog.SourceSn = item.OrderSn;
                        OrderSnByError = item.OrderSn;
                        inventoryLog.WarehouseId = inventory.WarehouseId;
                        inventoryLog.WarehouseName = inventory.WarehouseName;
                        inventoryLog.LocationCode = inventory.LocationCode;
                        inventoryLog.PalletBarcode = inventory.PalletBarcode;
                        inventoryLog.MaterialId = inventory.MaterialId;
                        inventoryLog.MaterialCode = inventory.MaterialCode;
                        inventoryLog.MaterialName = inventory.MaterialName;
                        inventoryLog.BaseUnitId = inventory.UnitId;
                        inventoryLog.BaseUnitName = inventory.UnitName;
                        inventoryLog.CreateDate = DateTime.Now;
                        inventoryLog.CreateUserId = item.CreateUserId;
                        inventoryLog.CreateUser = item.CreateUserName;
                        Context.TInventoryLogs.Add(inventoryLog);
                    }


                }
                if (Context.SaveChanges() <= 0)
                {
                    tran.Rollback();
                    message = "移库信息提交失败!";
                    return false;
                }
                tran.Commit();
                message = "移库信息提交成功!";
                return true;
            }
            catch (Exception ex)
            {
                tran.Rollback();
                message = "移库信息添加失败";
                return false;
            }



        }

        public bool UpTransferBinOrderStatus(TTransferBinOrderDetail m, out string message)
        {
            using var tran = Context.Database.BeginTransaction();
            try
            {
                message = "";
                TTransferBinOrderDTO transferBinOrderDTO = new TTransferBinOrderDTO();
                Context.TTransferBinOrderDetails.Update(m);
                if (Context.SaveChanges() <= 0)
                {
                    message = "更新明细数据失败";
                    return false;
                }
                transferBinOrderDTO.OrderSn = m.OrderSn;
                var existingOrders = Context.TTransferBinOrders.FirstOrDefault(o => o.OrderSn == m.OrderSn);
                if (existingOrders != null)
                {
                    existingOrders.Status = 4;
                    Context.TTransferBinOrders.Update(existingOrders);
                }
                transferBinOrderDTO.OrderDetailList.Add(m);
                List<TTransferBinOrderDTO> dto = new List<TTransferBinOrderDTO>();

                dto.Add(transferBinOrderDTO);
                string OrderSnByError = "";
                
                //修改仓位
                var inventories = Context.TInventories.Where(x => x.MaterialCode == m.MaterialCode && x.LocationCode == m.FromLocationName).ToList();
                foreach (var inventory in inventories)
                {
                    var existingOrder = Context.TInventories.FirstOrDefault(o => o.MaterialCode == m.MaterialCode);
                    if (existingOrder != null)
                    {
                        existingOrder.LocationName = m.FromLocationName;
                        existingOrder.LocationCode = m.FromLocationCode;
                        Context.TInventories.Update(existingOrder);
                    }

                    inventory.LocationCode = m.ToLocationCode;
                    Context.TInventories.Update(inventory);
                    if (Context.SaveChanges() <= 0)
                    {
                        message = "更新库存失败";
                        tran.Rollback();
                        return false;
                    }
                    TInventoryLog inventoryLog = new TInventoryLog();
                    inventoryLog.SourceType = 5;
                    inventoryLog.SourceSn = m.OrderSn;
                    OrderSnByError = m.OrderSn;
                    inventoryLog.WarehouseId = inventory.WarehouseId;
                    inventoryLog.WarehouseName = inventory.WarehouseName;
                    inventoryLog.LocationCode = inventory.LocationCode;
                    inventoryLog.PalletBarcode = inventory.PalletBarcode;
                    inventoryLog.MaterialId = inventory.MaterialId;
                    inventoryLog.MaterialCode = inventory.MaterialCode;
                    inventoryLog.MaterialName = inventory.MaterialName;
                    inventoryLog.BaseUnitId = inventory.UnitId;
                    inventoryLog.BaseUnitName = inventory.UnitName;
                    inventoryLog.CreateDate = DateTime.Now;
                    inventoryLog.CreateUserId = m.CreateUserId;
                    inventoryLog.CreateUser = m.CreateUserName;
                    Context.TInventoryLogs.Add(inventoryLog);
                }


                if (Context.SaveChanges() <= 0)
                {
                    tran.Rollback();
                    message = "移库信息提交失败!";
                    return false;
                }
                tran.Commit();
                message = "移库信息提交成功!";
                return true;
            }
            catch
            {
                tran.Rollback();
                message = "移库信息添加失败";
                return false;
            }

        }

        /// <summary>
        /// 获取单号状态为2的单号
        /// </summary>
        /// <returns></returns>
        public List<string> GetTransferBinOrderSn()
        {
            var list = Context.TTransferBinOrders.Where(x => x.Status == 2).OrderByDescending(x => x.CreateDate);
            List<string> result = new List<string>();
            foreach (var item in list)
            {
                string orderSn = item.OrderSn;
                result.Add(orderSn);
            }
            return result;
        }

        public List<TTransferBinOrderDetail> GetTransferBinOrderDetailsByOrderSn(string orderSn)
        {
            var list = Context.TTransferBinOrderDetails.Where(x => x.OrderSn == orderSn);
            List<TTransferBinOrderDetail> transferBinOrderDetails = new List<TTransferBinOrderDetail>();
            foreach (var item in list)
            {
                TTransferBinOrderDetail transferBinOrderDetails1 = new TTransferBinOrderDetail();
                transferBinOrderDetails.Add(item);
            }
            return transferBinOrderDetails;
        }

    }
}
